package com.vito.oa.act.print;

import com.itextpdf.text.BaseColor;

/**
 * Example written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/33795772/itext-not-generating-expected-pdf-format
 */
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactoryImp;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.vito.base.util.DateUtils;

import freemarker.template.Configuration;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
 
// No @WrapToTest because Windows fonts are used
public class ParseHtml {
    public static final String DEST = Configuration.class.getClassLoader().getResource("/").getPath()+"temp/out_put.pdf";
    public static final String HTML = Configuration.class.getClassLoader().getResource("/").getPath()+"temp/out_put.html";
    public static final String FONT_PATH = Configuration.class.getClassLoader().getResource("/").getPath()+"conf/SIMYOU.TTF";
 
    /**
     * Creates a PDF
     * @param file
     * @throws IOException
     * @throws DocumentException
     */
    public static synchronized void createPdf(String file) throws IOException, DocumentException {
        // step 1
        Document document = new Document(PageSize.A4);
        // step 2
        FileOutputStream fos=new FileOutputStream(file);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setInitialLeading(12);
        writer.setPageEvent(new HeaderFooter());
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new FileInputStream(HTML), Charset.forName("UTF-8"),new DefaultFontProvider(FONT_PATH));
        document.close();
        fos.close();

    }
    
    static class DefaultFontProvider extends FontFactoryImp {
    	  private String defaults;
    	  public DefaultFontProvider(String def) {
    		  defaults = def;
    	  }
    	  // I believe this is the correct override, but there are quite a few others.
    	  @Override
    	  public Font getFont(String fontName, String encoding, boolean embedded, float size, int style, BaseColor color, boolean cached) {
    	    if (fontName == null ) {
    	      fontName = defaults;
    	    }
//    	    return super.getFont(fontName, encoding, embedded, size, style, color, cached);
    		  
    		  BaseFont bf = null;  
    	        try {  
    	        	
    	            bf = BaseFont.createFont(FONT_PATH, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 
    	        } catch (Exception e) {  
    	            e.printStackTrace();  
    	        }  
    	        Font font = new Font(bf, size, style, color);  
    	        font.setColor(color);  
    	        return font; 
    	  }
    	}
    static class HeaderFooter extends PdfPageEventHelper {  
        String date;
    	public HeaderFooter(){
    		date = DateUtils.getDefaultDateTime();
        }
        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            PdfContentByte cb = writer.getDirectContent();
            Phrase header  = new Phrase(date);
            Phrase footer = new Phrase("--"+writer.getPageNumber()+"--");
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT,
                    header,
                    document.left(),
                    document.top() + 10, 0);
            ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT,
                    footer,
                    document.right() ,
                    document.bottom() - 10, 0);
        }
    }
}
